//
//  KSReturnedPurchaseViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/28.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import MJRefresh

/// 采购退货
class KSReturnedPurchaseViewController: KSBaseViewController {
    /// 列表
    @IBOutlet weak var tableView: UITableView!
    /// 退单类型
    @IBOutlet weak var chargeBackTypeBtn: UIButton!
    /// 退单状态
    @IBOutlet weak var chargeBackTypeStateBtn: UIButton!
    /// 分页
    private var page = 1
    /// 选择类型
    private var selectTypeState = "1"
    /// 选择状态
    private var selectOrderState = "-10"
    /// 选择类型、状态
    let chooseView = KSPickerOrderChooseView()
    /// 退单类型
    private var chargeBackTypeStruct = KSFilterStruct()
    /// 退单状态
    private var charegBackStateStruct = KSFilterStruct()
    /// 订单
    private var orderArray: [KSRefunListDataListModel] = []
    /// 没有数据显示
    private lazy var notHaveDataExistView: KSNotHaveDataExistView = {
        let view = KSNotHaveDataExistView(frame: CGRect(x: 0, y: 50, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight - 50))
        view.initView(imageName: "Common_ListEmpty", content: "暂无退货")
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "采购退货"
        
        self.initView()
        self.initData()
    }
    
    /// 初始化页面
    private func initView() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = KSColor.kColorViewBackground
        
        let nib = UINib(nibName: "KSReturnedPurchaseTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "KSReturnedPurchaseTableViewCell")
        
        self.tableView.estimatedRowHeight = 131
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        self.tableView.mj_footer.isHidden = true
        
        self.chooseView.delegate = self
        self.chooseView.isHidden = true
        self.view.addSubview(self.chooseView)
        self.chooseView.snp.makeConstraints { (make) in
            make.top.equalTo(50)
            make.left.right.bottom.equalTo(0)
        }
        
        self.view.addSubview(self.notHaveDataExistView)
        
        self.chargeBackTypeBtn.setIconInRightWithSpacing(spacing: 2)
        self.chargeBackTypeStateBtn.setIconInRightWithSpacing(spacing: 2)
    }
    
    /// 初始化数据
    private func initData() {
        self.chargeBackTypeStruct.descriptionArray = ["全部","退货","不退货"]
        self.chargeBackTypeStruct.valueArray = ["1","2","3"]
        self.charegBackStateStruct.descriptionArray = ["全部","待审核","等待验收","等待退款","退款完成","已驳回"]
        self.charegBackStateStruct.valueArray = ["-10","0","3","4","5","2"]
        
        self.startLoading()
        self.requestData()
    }
    
    @IBAction func chargeBackTypeBtnClick(_ sender: Any) {
        self.chargeBackTypeBtn.isSelected = true
        if self.chargeBackTypeStateBtn.isSelected {
            self.chargeBackTypeStateBtn.isSelected = false
        }
        
        if !self.notHaveDataExistView.isHidden {
            self.view.insertSubview(self.chooseView, aboveSubview: self.notHaveDataExistView)
        }
        self.chooseView.changeDataArray(array: self.chargeBackTypeStruct.descriptionArray, selectRow: self.chargeBackTypeStruct.selectRow)
    }
    
    @IBAction func charegBackStateBtnClick(_ sender: Any) {
        self.chargeBackTypeStateBtn.isSelected = true
        if self.chargeBackTypeBtn.isSelected {
            self.chargeBackTypeBtn.isSelected = false
        }
        
        if !self.notHaveDataExistView.isHidden {
            self.view.insertSubview(self.chooseView, aboveSubview: self.notHaveDataExistView)
        }
        self.chooseView.changeDataArray(array: self.charegBackStateStruct.descriptionArray, selectRow: self.charegBackStateStruct.selectRow)
    }
    
    @objc func loadNewData() {
        self.page = 1
        self.requestData()
    }
    
    @objc func loadMoreData() {
        self.page += 1
        self.requestData()
    }
    
    private func requestData() {
        let parameter: [String : Any] = ["select_type" : "\(KSUserDefaultsTools.getUserType())", "page" : self.page, "is_shipment" : selectTypeState, "status" : [self.selectOrderState]]
        self.request.requestRefundList(parameters: parameter)
    }
    
    /// KSRequestDelegate
    
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        
        if apiType == KSApiType.KSRefundList {
            let orderModel = KSRefundListModel.deserialize(from: result)
            self.analyOrderList(model: (orderModel?.data)!)
        }
    }
    
    override func requestFaile(code: Int, message: String, apiType: KSApiType) {
        super.requestFaile(code: code, message: message, apiType: apiType)
        if apiType == KSApiType.KSRefundList {
            if self.page > 1 {
                self.page -= 1
            }
            tableView.mj_header.endRefreshing()
            tableView.mj_footer.endRefreshing()
        }
    }
    
    // 订单解析
    fileprivate func analyOrderList(model: KSRefunListDataModel) {
        if self.page == 1 {
            self.orderArray.removeAll()
            if (model.list)!.count > 0 {
                self.notHaveDataExistView.isHidden = true
                
                self.orderArray = (model.list)!
                tableView.mj_footer.isHidden = false
            } else {
                self.notHaveDataExistView.isHidden = false
            }
        } else {
            if (model.list)!.count > 0 {
                self.orderArray = self.orderArray + (model.list)!
                tableView.mj_footer.isHidden = false
            } else {
                if self.page > 1 {
                    self.page -= 1
                }
                
                self.progressHUD.showMessage(text: "没有更多订单")
            }
        }
        
        tableView.reloadData()
        tableView.mj_header.endRefreshing()
        tableView.mj_footer.endRefreshing()
    }
}

// MARK: - KSChooseScreenTypeDelegate

extension KSReturnedPurchaseViewController: KSChooseScreenTypeDelegate {
    func chooseScreenType(selectRow: NSInteger) {
        if self.chargeBackTypeBtn.isSelected {
            self.chargeBackTypeStruct.selectRow = selectRow
            self.selectTypeState = self.chargeBackTypeStruct.valueArray[selectRow]
            self.chargeBackTypeBtn.setTitle(self.chargeBackTypeStruct.descriptionArray[selectRow], for: .normal)
            self.chargeBackTypeBtn.setIconInRightWithSpacing(spacing: 2)
            self.chargeBackTypeBtn.isSelected = false
        }
        
        if self.chargeBackTypeStateBtn.isSelected {
            self.charegBackStateStruct.selectRow = selectRow
            self.selectOrderState = self.charegBackStateStruct.valueArray[selectRow]
            self.chargeBackTypeStateBtn.setTitle(self.charegBackStateStruct.descriptionArray[selectRow], for: .normal)
            self.chargeBackTypeStateBtn.setIconInRightWithSpacing(spacing: 2)
            self.chargeBackTypeStateBtn.isSelected = false
        }
        
        self.startLoading()
        self.requestData()
    }
}

extension KSReturnedPurchaseViewController: UITableViewDelegate, UITableViewDataSource {
    
    // UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.orderArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    // UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 131
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSReturnedPurchaseTableViewCell", for: indexPath) as! KSReturnedPurchaseTableViewCell
        cell.setDataWithModel(model: orderArray[indexPath.section])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let model = orderArray[indexPath.section]
            let vc = KSSubmitRefundViewController()
            vc.orderNumber = model.order_number!
            vc.goodsDataArray = model.refund_goods!
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            let model = orderArray[indexPath.row]
            let vc = KSRefundDetailViewController()
            vc.refundNumber = model.order_number!
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}
